package com.hooware.service.impl;

import com.hooware.dao.IUserDao;
import com.hooware.domain.Role;
import com.hooware.domain.UserInfo;
import com.hooware.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("userService")
public class UserServiceImpl implements IUserService {
    @Autowired
    private IUserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = userDao.findByUsername(username);
        User user = null;
        if (userInfo != null) {
            user = new User(userInfo.getUsername(),userInfo.getPassword(), (userInfo.getStatus()==0?false:true),true,true,true,getAuthority(userInfo));
        }
        System.out.println("===============封装用户为===========:" + user);
        return user;
    }

    @Override
    public List<UserInfo> findAll() {
        return userDao.findAll();
    }

    @Override
    public void saveUser(UserInfo userInfo) {
        userDao.saveUser(userInfo);
    }

    @Override
    public UserInfo findById(String id) {
        return userDao.findById(id);
    }

    @Override
    public List<Role> findOtherRoles(String id) {
        return userDao.findOtherRoles(id);
    }

    @Override
    public void addRoleToUser(String uid, String[] rids) {
        for (String rid : rids) {
            userDao.addRoleToUser(uid,rid);
        }
    }

    /**
     * 用户角色授权
     * @return
     */
    private List<SimpleGrantedAuthority> getAuthority(UserInfo userInfo) {
        List<SimpleGrantedAuthority> list = new ArrayList<>();
        List<Role> rolesList = userInfo.getRoles();
        for (Role role : rolesList) {
            list.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleName()));
        }
        System.out.println("_________用户权限+++++: " + list);
        return list;
    }
}
